package com.linxz.framework.base;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.linxz.commonlib.ARouterManager;
import com.linxz.framework.R;
import com.linxz.framework.ui.loader.LoadingView;
import com.linxz.framework.ui.statebar.StatusBarCompat;

import io.reactivex.subjects.PublishSubject;

/**
 * @author Linxz
 * 创建日期：2019年02月20日 19:49
 * version：1.0.0
 * 描述：
 */
public abstract class BaseActivity extends AppCompatActivity implements Thread.UncaughtExceptionHandler {
    public final static int BASE_REQUEST_CODE=1001;
    protected BaseActivity activity;
    public final PublishSubject<ActivityLifeCycleEvent> lifecycleSubject = PublishSubject.create();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ARouterManager.inject(this);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        activity = this;
        AppActivityManager.getInstance().addActivity(this);
        lifecycleSubject.onNext(ActivityLifeCycleEvent.CREATE);
        Bundle b = getIntent().getBundleExtra("Bundle");
        onGetBundle(b);
    }

    public void onGetBundle(Bundle bundle) {
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        lifecycleSubject.onNext(ActivityLifeCycleEvent.PAUSE);
        super.onPause();
    }

    @Override
    protected void onStop() {
        lifecycleSubject.onNext(ActivityLifeCycleEvent.STOP);
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        lifecycleSubject.onNext(ActivityLifeCycleEvent.DESTROY);
        AppActivityManager.getInstance().removeActivity(this);
        super.onDestroy();
    }

    @Override
    public void finish() {
        super.finish();
    }

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        AppActivityManager.getInstance().cleanActivity();
    }


    protected abstract void initUI();

    protected abstract void initData();

    protected void setListener() {
    }

    public void showToast(String msg) {
        Toast.makeText(activity, msg + "", Toast.LENGTH_LONG).show();
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideKeyboard(v, ev)) {
                hideKeyboard(v.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上，和用户用轨迹球选择其他的焦点
        return false;
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     *
     * @param token
     */
    private void hideKeyboard(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    public String getTag() {
        return this.getClass().getSimpleName();
    }


    public void setActionBar(int imgBackResId,Integer tittleResId,String tittleName){
        try {
            ImageView imageView = findViewById(imgBackResId);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
            if (tittleResId != null) {
                TextView tvTittle = findViewById(tittleResId);
                tvTittle.setText(tittleName);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setActionBar(int imgBackResId, Integer tittleResId, String tittleName, Integer rightResId, String right, View.OnClickListener onClickListener){
        try {
            ImageView imageView = findViewById(imgBackResId);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
            if (tittleResId != null) {
                TextView tvTittle = findViewById(tittleResId);
                tvTittle.setText(tittleName);
            }
            if (rightResId!=null){
                TextView tvRight=findViewById(rightResId);
                tvRight.setText(right);
                tvRight.setOnClickListener(onClickListener);
                tvRight.setVisibility(View.VISIBLE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void initStatebar() {
        if ("UserMainActivity".equals(activity.getClass().getSimpleName())) {
            //透明状态栏
            setTranslucentActionBar();
        } else {
            setNormalActionBar();
        }
    }

    public void setTranslucentActionBar(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        } else {
            StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(this, R.color.color_99999));
        }
    }

    public void setNormalActionBar(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(this, R.color.white));
        } else {
            StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(this, R.color.color_99999));
        }
    }

    public void showLoading(String msg){
        LoadingView.getInstance().showLoading(activity,msg);
    }

    public void hideLoading(){
        LoadingView.getInstance().hideLoading();
    }

}
